#!/usr/bin/env python

# Copyright Jamie Iles, 2017
#
# This file is part of s80x86.
#
# s80x86 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# s80x86 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with s80x86.  If not, see <http://www.gnu.org/licenses/>.

import argparse
import sys

from py8086sim.Cpu import GPR


def load(cpu, program, cs, ip):
    cpu.reset()

    cpu.write_reg(GPR.CS, cs)
    with open(program) as b:
        bytevec = [ord(v) for v in b.read()]
        if len(bytevec) % 2 == 1:
            bytevec.append(0)
        wordvec = []
        for a, b in zip(bytevec[::2], bytevec[1::2]):
            wordvec.append(a | (b << 8))
        cpu.write_vector16(cs, ip, wordvec)

    cpu.write_reg(GPR.IP, ip)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('backend')
    parser.add_argument('program')
    parser.add_argument('cs')
    parser.add_argument('ip')
    args = parser.parse_args()

    cpu = getattr(sys.modules['py8086sim.Cpu'], args.backend)(args.program)

    load(cpu, args.program, int(args.cs, 0), int(args.ip, 0))
